package com.lc.zpyh.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.lc.base.BaseDialog;
import com.lc.zpyh.R;
import com.lc.zpyh.app.TitleBarFragment;
import com.lc.zpyh.http.glide.GlideApp;
import com.lc.zpyh.http.request.SelectMerchantsCSApi;
import com.lc.zpyh.http.request.SelectMyCartCountApi;
import com.lc.zpyh.http.request.SelectMyMessageNoCountApi;
import com.lc.zpyh.http.response.SelectMyCartCountBean;
import com.lc.zpyh.http.response.SelectMyMessageNoCountBean;
import com.lc.zpyh.http.response.SelectRecommendMerchantsBean;
import com.lc.zpyh.other.IntentKey;
import com.lc.zpyh.ui.activity.MainActivity;
import com.lc.zpyh.ui.activity.ShopCarActivity;
import com.lc.zpyh.ui.activity.home.AddressSearchActivity;
import com.lc.zpyh.ui.activity.home.FoodNewsActivity;
import com.lc.zpyh.ui.activity.home.SearchActivity;
import com.lc.zpyh.ui.activity.mine.LoginCodeActivity;
import com.lc.zpyh.ui.activity.supermarket.BusinessActivity;
import com.lc.zpyh.util.BigDecimalUtils;
import com.lc.zpyh.util.CourseUtils;
import com.lc.zpyh.util.SPUtil;
import com.lc.zpyh.util.constant.EvenConstant;
import com.lc.zpyh.util.eventbus.Event;
import com.lc.zpyh.widget.UIHelper;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

public class SupermarketFragment extends TitleBarFragment<MainActivity> {
    @BindView(R.id.tv_home_address)
    TextView tvHomeAddress;
    @BindView(R.id.tv_new_num)
    TextView tvNewNum;
    @BindView(R.id.tv_cart_num)
    TextView tvCartNnum;


    @BindView(R.id.layout_refresh)
    TwinklingRefreshLayout refreshLayout;
    @BindView(R.id.rv_supermarket)
    RecyclerView rvSupermarket;
    @BindView(R.id.ll_inTheEnd)
    LinearLayout llInTheEnd;
    @BindView(R.id.car_iv)
    ImageView carIv;
    private static final String TAG = "SupermarketFragment";
    private BaseQuickAdapter<SelectRecommendMerchantsBean.ListBean.DataBean, BaseViewHolder> adapter;
    private String schoolId;
    private BaseDialog mWaitDialog;
    private List<SelectRecommendMerchantsBean.ListBean.DataBean> dataBeanList =new ArrayList<>();
    private int page = 1;
    private int total;
    private int newscount;
    private String userid;
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_supermarket;
    }

    @Override
    protected void initView() {


    }
    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setUpAdapter("1",SPUtil.get(getContext(), IntentKey.ADDRESSID,""));
//
        if(SPUtil.get(getContext(), IntentKey.USERID, "").equals("")){
            tvNewNum.setVisibility(View.GONE);
        }
        if ( SPUtil.get(getContext(),IntentKey.NEWSCOUNT,"").isEmpty()||SPUtil.get(getContext(),IntentKey.NEWSCOUNT,"").equals("0")){

            tvNewNum.setVisibility(View.GONE);
        }else {
            tvNewNum.setVisibility(View.VISIBLE);

            tvNewNum.setText(SPUtil.get(getContext(),IntentKey.NEWSCOUNT,"")+"");
            newscount = Integer.parseInt(SPUtil.get(getContext(),IntentKey.NEWSCOUNT,""));
        }
        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                page = 1;
                setUpAdapter(page + "",SPUtil.get(getContext(), IntentKey.ADDRESSID,""));
                refreshLayout.finishRefreshing();

            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                refreshLayout.finishLoadmore();
//                if (!TextUtils.isEmpty(goods_classify_id)) {

                page++;
                Log.e(TAG, "onLoadMore: "+ page);
                if (dataBeanList.size() < total) {
                    setUpAdapter(page + "",SPUtil.get(getContext(), IntentKey.ADDRESSID,""));
                } else {
                    Log.e(TAG, "refreshLayout: "+ page);
                    refreshLayout.setEnableLoadmore(false);
                    llInTheEnd.setVisibility(View.VISIBLE);
                }
//                }

            }
        });


    }
    @Override
    protected void initData() {


    }

    @OnClick({R.id.tv_home_address, R.id.ll_seach, R.id.rl_shopping_cart,R.id.car_iv})
    @Override
    public void onStart() {
        super.onStart();
        tvHomeAddress.setText( SPUtil.get(getContext(), IntentKey.ADDRESS,""));

        if (!SPUtil.get(getContext(), IntentKey.ADDRESSID, "").isEmpty() && !SPUtil.get(getContext(), IntentKey.USERID, "").isEmpty()) {
            selectMyCartCount();
        }
        if (SPUtil.get(getContext(), IntentKey.CAR_COUNT, "").isEmpty()||SPUtil.get(getContext(), IntentKey.CAR_COUNT, "")==null||SPUtil.get(getContext(), IntentKey.CAR_COUNT, "").equals("0")){
            tvCartNnum.setVisibility(View.GONE);
        }else {
            tvCartNnum.setVisibility(View.VISIBLE);
            tvCartNnum.setText(SPUtil.get(getContext(), IntentKey.CAR_COUNT, ""));
        }
        selectMessages();
    }
    private void selectMyCartCount() {
        if (SPUtil.get(getContext(), IntentKey.USERID, "") == null || SPUtil.get(getContext(), IntentKey.USERID, "").isEmpty()) {
            userid = "";
        } else {
            userid = SPUtil.get(getContext(), IntentKey.USERID, "");
        }
        EasyHttp.post(this)
                .api(new SelectMyCartCountApi().setSchoolId(SPUtil.get(getContext(), IntentKey.ADDRESSID, "")).setUserId(userid)).request(new HttpCallback<SelectMyCartCountBean>(this) {

            @Override
            public void onSucceed(SelectMyCartCountBean data) {
                if (data.getCode() == 0) {
                    SPUtil.put(getContext(), IntentKey.CAR_COUNT, data.getList() + "");

                    if (SPUtil.get(getContext(), IntentKey.CAR_COUNT, "").isEmpty()||SPUtil.get(getContext(), IntentKey.CAR_COUNT, "")==null||SPUtil.get(getContext(), IntentKey.CAR_COUNT, "").equals("0")){
                        tvCartNnum.setVisibility(View.GONE);
                    }else {
                        tvCartNnum.setVisibility(View.VISIBLE);
                        tvCartNnum.setText(SPUtil.get(getContext(), IntentKey.CAR_COUNT, ""));
                    }
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }
    @OnClick({R.id.tv_home_address, R.id.ll_seach, R.id.rl_shopping_cart,R.id.car_iv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_home_address:

                UIHelper.startActivity(getContext(), AddressSearchActivity.class);
                break;
            case R.id.ll_seach:
                UIHelper.startActivity(getContext(), SearchActivity.class);
                break;
            case R.id.rl_shopping_cart:

                    UIHelper.startActivity(getContext(), FoodNewsActivity.class);

                break;
            case R.id.car_iv:
                if (!CourseUtils.isNotNullOrEmpty(SPUtil.get(getContext(),IntentKey.USERID,""))){
                    startActivity(LoginCodeActivity.class);
                    return;
                }
                UIHelper.startActivity(getContext(), ShopCarActivity.class);
                break;
        }
    }



    //   超市商家
    private void setUpAdapter(String page,String schoolId) {
        Log.e(TAG, "setUpAdapter: "+ SPUtil.get(getContext(), IntentKey.ADDRESSID,""));
        EasyHttp.post(this)
                .api(new SelectMerchantsCSApi().setSchoolId(schoolId).setPageNum(page).setPageSize("10")).request(new HttpCallback<SelectRecommendMerchantsBean>(this) {

            @Override
            public void onSucceed(SelectRecommendMerchantsBean data) {
                if (data.getCode()==0){
                    total=data.getList().getCount();
                    if (adapter==null) {
                        dataBeanList.clear();

                        dataBeanList.addAll(data.getList().getData());
                        adapter = new BaseQuickAdapter<SelectRecommendMerchantsBean.ListBean.DataBean, BaseViewHolder>
                                (R.layout.item_shop_goods, dataBeanList) {

                            @Override
                            protected void convert(BaseViewHolder baseViewHolder, SelectRecommendMerchantsBean.ListBean.DataBean dataBean) {
                                if (dataBean.getMerchantCoupons() != null ) {
                                    if (dataBean.getMerchantCoupons().size() > 0 && dataBean.getMerchantCoupons().size() < 2) {

                                        baseViewHolder.setText(R.id.tv_tag_type1, "满"+BigDecimalUtils.div(dataBean.getMerchantCoupons().get(0).getMeetTheConditions()+"","100",0)+"减"+BigDecimalUtils.div(dataBean.getMerchantCoupons().get(0).getCreditFor()+"","100",0));
                                        baseViewHolder.setVisible(R.id.tv_tag_type1, true);
                                        baseViewHolder.setVisible(R.id.tv_tag_type2, false);
                                    } else if (dataBean.getMerchantCoupons().size() >= 2) {
                                        baseViewHolder.setText(R.id.tv_tag_type1, "满"+ BigDecimalUtils.div(dataBean.getMerchantCoupons().get(0).getMeetTheConditions()+"","100",2)+"减"+BigDecimalUtils.div(dataBean.getMerchantCoupons().get(0).getCreditFor()+"","100",0));
                                        baseViewHolder.setText(R.id.tv_tag_type2, "满"+BigDecimalUtils.div(dataBean.getMerchantCoupons().get(1).getMeetTheConditions()+"","100",2)+"减"+BigDecimalUtils.div(dataBean.getMerchantCoupons().get(1).getCreditFor()+"","100",0));
                                        baseViewHolder.setVisible(R.id.tv_tag_type1, true);
                                        baseViewHolder.setVisible(R.id.tv_tag_type2, true);
                                    }
                                } else {
                                    baseViewHolder.setVisible(R.id.tv_tag_type1, false);
                                }
                                baseViewHolder.setText(R.id.tv_shop_name, dataBean.getName());
                                if (dataBean.getStatus()==0){
                                    baseViewHolder.setGone(R.id.tv_status,true);
                                }else {
                                    baseViewHolder.setVisible(R.id.tv_status,true);
                                }

                                if (dataBean.getImg() != null) {
                                    GlideApp.with(requireContext()).load(IntentKey.ORDER_IMAGE+dataBean.getImg()).apply(new RequestOptions().placeholder(R.mipmap.zhanweiicon01).error(R.mipmap.zhanweiicon01)).into((ImageView) baseViewHolder.getView(R.id.img_shop));

                                }
                                baseViewHolder.setText(R.id.tv_xiaoliang, "月销量"+dataBean.getSales());

                            }


                        };


                        rvSupermarket.setAdapter(adapter);
                        adapter.setOnItemClickListener(new OnItemClickListener() {
                            @Override
                            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {

                                if (!CourseUtils.isNotNullOrEmpty(SPUtil.get(getContext(),IntentKey.USERID,""))){
                                    startActivity(LoginCodeActivity.class);
                                    return;
                                }
                               startActivity(new Intent(getContext(), BusinessActivity.class).putExtra("id",dataBeanList.get(position).getId()+""));
                            }
                        });
                    }else {
                        if (!page.equals("1")) {
                            dataBeanList.addAll(data.getList().getData());
                            adapter.notifyDataSetChanged();
                        }else {
                            dataBeanList.clear();
                            dataBeanList.addAll(data.getList().getData());
                            adapter.notifyDataSetChanged();
                        }

                    }
                    if (dataBeanList.size()>0) {
                        refreshLayout.setEnableLoadmore(true);
                        llInTheEnd.setVisibility(View.GONE);
                    } else {
                        refreshLayout.setEnableLoadmore(false);
                        View emptyview = View.inflate(getContext(), R.layout.empty_emptylayout, null);
                        adapter.setEmptyView(emptyview);
//                        llInTheEnd.setVisibility(View.VISIBLE);
                    }
                }


            }
            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });






    }
    private void selectMessages() {
        if(SPUtil.get(getContext(), IntentKey.USERID, "").equals("")){
            tvNewNum.setVisibility(View.GONE);
            return;
        }

        EasyHttp.post(this)
                .api(new SelectMyMessageNoCountApi().setUserid(SPUtil.get(getContext(), IntentKey.USERID, ""))).request(new HttpCallback<SelectMyMessageNoCountBean>(this) {

            @Override
            public void onSucceed(SelectMyMessageNoCountBean data) {
                if (data.getCode()==0) {
                    if (data.getCount() == 0) {

                        tvNewNum.setVisibility(View.GONE);
                    } else {
                        tvNewNum.setVisibility(View.VISIBLE);

                        newscount = data.getCount();
                        tvNewNum.setText(newscount + "");
                    }
                }

            }
            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }
    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(Event event) {
        super.receiveEvent(event);
        if(event.getCode()== EvenConstant.QUWANSHANXIN){
            tvHomeAddress.setText(event.getData()+"");
        }else if (event.getCode()== EvenConstant.QUWANSHANXINID){
            schoolId = (String) event.getData();

            Log.e("@@", "receiveEvent: "+schoolId);
            setUpAdapter(page+"",schoolId);
        }
    }

}
